/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import Flutter

class ScreenOrientationStreamHandler: NSObject, FlutterStreamHandler {
    private var eventSink: FlutterEventSink?
    private var lastOrientation = -1

    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        eventSink = events
        NotificationCenter.default.addObserver(self, selector: #selector(orientationChanged), name: UIDevice.orientationDidChangeNotification, object: nil)
        UIDevice.current.beginGeneratingDeviceOrientationNotifications()
        return nil
    }

    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        UIDevice.current.endGeneratingDeviceOrientationNotifications()
        NotificationCenter.default.removeObserver(self)
        return nil
    }

    @objc private func orientationChanged() {
        var orientation = -1
        switch UIApplication.shared.statusBarOrientation {
        case .portrait:
            orientation = 0
        case .portraitUpsideDown:
            orientation = 0
        case .landscapeLeft:
            orientation = 1
        case .landscapeRight:
            orientation = 1
        default:
            orientation = 0
        }
        if orientation != lastOrientation {
            lastOrientation = orientation
            eventSink!(lastOrientation)
        }
    }
}
